package com.example.time_bank_demo.dao;

import com.example.time_bank_demo.model.TbUser;
import com.example.time_bank_demo.params.UserCreateParams;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.util.Objects;


//标记为 service

//alt + enter  可以快速互换 构造方法  快捷导航  alt+ enter  +enter

// 把方法抽象出来 给其他的类用
@Service
public class TbUserDao {

    private final JdbcTemplate jdbcTemplate;

    public TbUserDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    public TbUser selectUserByPhone(String phone) {
        String sql = "SELECT * FROM tb_user WHERE phone = ?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(TbUser.class), phone);
    }

    public TbUser insertUser(UserCreateParams createParams) {

        //插入数据库
        String sql = "INSERT INTO tb_user (`name`,phone,email,`password`,nick_name,identity_card,provinces,cities,districts,address_detail,invite_code,type )  VALUES (?,?,?,?,?,?,?,?,?,?,?,?);";

        // 存 你这条插入的数据的 自增主键
        GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(con -> {
            PreparedStatement ps = con.prepareStatement(sql, new String[]{"id"});
            ps.setString(1, createParams.getName());
            ps.setString(2, createParams.getPhone());
            ps.setString(3, createParams.getEmail());
            ps.setString(4, createParams.getPassword());
            ps.setString(5, createParams.getNickName());
            ps.setString(6, createParams.getIdentityCard());
            ps.setString(7, createParams.getProvinces());
            ps.setString(8, createParams.getCities());
            ps.setString(9, createParams.getDistricts());
            ps.setString(10, createParams.getAddressDetail());
            ps.setString(11, createParams.getInviteCode());
            ps.setString(12, createParams.getType());
            return ps;
        }, generatedKeyHolder);
        //如果是自增加主键 这里会放入自增 主键的 id
        Integer id = Objects.requireNonNull(generatedKeyHolder.getKey()).intValue();
        //查询数据库
        String querySql = "SELECT * FROM tb_user WHERE id = ?";
        return jdbcTemplate.queryForObject(querySql, new BeanPropertyRowMapper<>(TbUser.class), id);
    }

}
